const app = getApp();
const MAX_COUNT_IMAGE = 9;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    authLocationTips: false,
    pageType: 1, // 1添加 2编辑
    equipment_name: "",
    equipmentTypes: [], //设备类型
    equipmentTypeIndex: "",
    equipment_number: "", //设备编号
    villages: [],
    villageIndex: "",
    address: "",
    latitude: "",
    longitude: "",
    all_url_arrs: [],
    url_arrs: [],
    max_count_img: MAX_COUNT_IMAGE,
    partners: [], //所属合伙人
    partnerIndex: '', //选择的合伙人index
  },






  getCurrentPartner() {
    return new Promise((resolve, reject) => {
      app.ajax({
        url: "Manage/Equipment/getPartnerList",
        success: res => {
          if (res.data.code > 0) {
            resolve(res.data.data)
          }
        },
        error: e => {
          reject("网络错误")
        }
      })
    })
  },

  //获取设备类型
  getElementType: function () {
    return new Promise((resolve, reject) => {
      app.ajax({
        url: 'Common/Common/getEquipmentType',
        method: "POST",
        data: {},
        success: function (res) {
          if (res.data.code == 1000) {
            resolve(res.data.data)
          } else {
            reject(res.data.message || '服务器异常，请稍后再试')
          }
        },
        error: e => {
          reject("网络错误");
        }
      })
    })

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    Promise.all([this.getCurrentPartner(), this.getElementType()]).then(([partners, equipmentTypes]) => {
      this.setData({
        partners,
        equipmentTypes
      })
      this.deviceInfo(options.eq_sn);
    }).catch(e => {
      app.showToast(e)
    })
  },
  //获取设备信息
  deviceInfo(sn) {

    app.ajax({
      url: 'Manage/Equipment/deviceInfo',
      data: {
        sn
      },
      success: res => {
        if (res.data.code == 1000) {
          const source = res.data.data;
          let partnerIndex = this.data.partners.findIndex(current => current.s_number == source.s_number);
          let equipment_type = this.data.equipmentTypes.findIndex(current => current.id == source.equipment_type);
          this.getPartnerOfVillage(source);
          this.equipment_id = source.id;
          this.setData({
            equipment_name: source.equipment_name,
            equipment_number: source.equipment_number,
            address: source.address,
            url_arrs: source.equipment_img,
            all_url_arrs: source.equipment_img_whole,
            partnerIndex: ~partnerIndex ? partnerIndex : '',
            equipmentTypeIndex: ~equipment_type ? equipment_type : '',
            latitude: source.latitude,
            longitude: source.longitude,
          })
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },

  //根据合伙人id去查询园区 

  getPartnerOfVillage(source) {
    app.ajax({
      url: "Manage/Equipment/repairPersonnelPark",
      data: {
        partner_id: source.partner_id
      },
      success: res => {
        if (res.data.code > 0) {
          const villages = res.data.data[0].villageData;
          let index = villages.findIndex(item => item.village_name == source.village_name);
          if (index <= -1) {
            villages.unshift({
              province: source.province,
              city: source.city,
              area: source.area,
              province_name: source.province_name,
              city_name: source.city_name,
              area_name: source.area_name,
              village_name: source.village_name,
              address: source.address,
              lng: source.longitude,
              lat: source.latitude
            })
            index = 0;
          }
          this.setData({
            villages,
            villageIndex: index
          })
        } else {
          app.showToast(res.data.message);
        }
      },
      error: e => {
        app.showToast("网络错误")
      }
    })
  },



  scanCode(e) {
    const name = e.currentTarget.dataset.name;
    app.scanDeviceCode().then(res => {
      this.setData({
        [name]: res
      })
    }).catch(e => {
      app.showToast("扫码失败")
    })
  },





  chooseImg() {
    let pictrues = this.data.all_url_arrs;
    let count = MAX_COUNT_IMAGE - pictrues.length;
    wx.chooseImage({
      count,
      success: res => {
        const tempFilePaths = res.tempFilePaths;
        wx.showLoading({
          title: '资源上传中',
        })
        for (let i = 0; i < tempFilePaths.length; i++) {
          this.uploadFile(tempFilePaths[i], i, tempFilePaths.length - 1);
        }
      }
    })
  },

  uploadFile: function (tempFilePath, i, len) {
    var that = this;
    wx.uploadFile({
      url: app.globalData._url + 'Common/Common/upload',
      filePath: tempFilePath,
      name: 'file',
      success(res) {
        var source = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}");
        if (source.code == 1000) {
          let all_url_arrs = that.data.all_url_arrs;
          let url_arrs = that.data.url_arrs;
          url_arrs.unshift(source.data.url);
          all_url_arrs.unshift(source.data.all_url);
          console.log(all_url_arrs, url_arrs);
          if (i == len) {
            wx.hideLoading();
          }
          that.setData({
            all_url_arrs,
            url_arrs
          })
        } else {
          app.showToast(`第${i+1}张图片上传失败`);
        }
      }
    })
  },

  deleteImg(e) {
    const index = e.currentTarget.dataset.index;
    let all_url_arrs = this.data.all_url_arrs;
    let url_arrs = this.data.url_arrs;
    all_url_arrs.splice(index, 1)
    url_arrs.splice(index, 1)
    this.setData({
      all_url_arrs,
      url_arrs
    })
  },

  navMapSetting() {
    if (this.data.villageIndex === "") {
      app.showToast("请先选择园区", "none", 2000, function () {});
      return;
    }
    wx.getSetting({
      success: settingRes => {
        if (settingRes.errMsg === "getSetting:ok") {
          const setting = settingRes.authSetting;
          if (setting["scope.userLocation"] == undefined || setting["scope.userLocation"]) {
            if (!this.data.latitude || !this.data.longitude) {
              wx.getLocation({
                type:"gcj02",
                success: results => {
                  this.setData({
                    latitude: results.latitude,
                    longitude: results.longitude
                  })
                  this.openLocation();
                },
                fail: res => {
                  app.showToast("请检查是否打开手机定位功能");
                }
              })
            } else {
              this.openLocation();
            }
          } else if (setting["scope.userLocation"] == false) {
            this.setData({
              authLocationTips: true
            })
          }
        }
      },
      fail: e => {
        app.showToast("getSetting fail");
      }

    })
  },

  openLocation() {
    wx.chooseLocation({
      latitude: this.data.latitude - 0,
      longitude: this.data.longitude - 0,
      success: res => {
        if (res.errMsg === "chooseLocation:ok") {
          this.setData({
            address: res.name,
            longitude: res.longitude,
            latitude: res.latitude
          })
        }
        console.log(res, "results")
      },
      fail: e => {
        if (e.errMsg === "chooseLocation:fail auth deny") {
          this.setData({
            authLocationTips: true
          })
        }
      }
    })
  },

  handleOpenSetting() {
    wx.openSetting({
      success: res => {
        if (res.errMsg === "openSetting:ok") {
          if (res.authSetting["scope.userLocation"]) {
            this.setData({
              authLocationTips: false
            })
            this.openLocation()
          }
        }
      },
      fail: e => {
        app.showToast("打开设置失败");
      }
    })
  },


  closeLocationTips() {
    this.setData({
      authLocationTips: false
    })
  },

  handlePicker(e) {
    const name = e.currentTarget.dataset.name;
    this.setData({
      [name]: e.detail.value
    })
  },


  pickVillage(e) {
    const name = e.currentTarget.dataset.name;
    const villages = this.data.villages;
    const value = e.detail.value;
    this.setData({
      [name]: value,
      address: villages[value].address,
      longitude: villages[value].lng,
      latitude: villages[value].lat,
    })
  },


  //提交修改参数
  formSubmit: function (e) {
    const formVal = e.detail.value;
    if (formVal.equipment_name == '') {
      app.showToast("设备名不能为空");
      return false;
    } else if (this.data.equipmentTypeIndex === '') {
      app.showToast("请选择设备类型");
      return false;
    } else if (this.data.villageIndex === '') {
      app.showToast("请选择园区");
      return false;
    } else if (formVal.address == '') {
      app.showToast("请填写安装地址");
      return false;
    } else if (!this.data.latitude || !this.data.longitude) {
      app.showToast("请点击定位图标定位", 'none', 3000);
      return false;
    }
    let village = this.data.villages[this.data.villageIndex];
    wx.showLoading({
      mask: true,
    })
    app.ajax({
      url: "Manage/Equipment/saveEquipment",
      data: {
        id: this.equipment_id,
        sn: this.data.equipment_number,
        eq_name: formVal.equipment_name,
        s_number: this.data.partners[this.data.partnerIndex].s_number,
        province: village.province,
        city: village.city,
        area: village.area,
        province_name: village.province_name,
        city_name: village.city_name,
        area_name: village.area_name,
        village_name: village.village_name,
        address: formVal.address,
        longitude: this.data.longitude,
        latitude: this.data.latitude,
        equipment_type: this.data.equipmentTypes[this.data.equipmentTypeIndex].id,
        equipment_img: this.data.url_arrs,
      },
      success: res => {
        wx.hideLoading()
        if (res.data.code == 1000) {
          app.showToast(res.data.message, "success");
          setTimeout(() => {
            let pages = getCurrentPages();
            let targetPage = pages[pages.length - 2];
            targetPage.reloadData();
            wx.navigateBack({
              delta: 1
            })
          }, 1500);
        } else {
          app.showToast(res.data.message);
        }
      },
      error: e => {
        wx.hideLoading();
        app.showToast("网络错误")
      }
    })
  },


})